import axios from 'axios';
import { ElMessage } from 'element-plus';

// 创建 axios 实例
const apiClient = axios.create({
  baseURL: process.env.VUE_APP_API_BASE_URL || 'http://localhost:3000',
  timeout: 15000,
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json',
    'X-Requested-With': 'XMLHttpRequest'
  }
});

// 请求拦截器
apiClient.interceptors.request.use(
  (config) => {
    // 添加 Token 到请求头
    const token = localStorage.getItem('token');
    if (token && config.headers) {
      config.headers.Authorization = `Bearer ${token}`;
    }

    // 处理 FormData 请求
    if (config.data instanceof FormData) {
      config.headers['Content-Type'] = 'multipart/form-data';
    }

    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
apiClient.interceptors.response.use(
  (response) => {
    // 处理成功响应（如需要统一数据格式）
    if (response.data.code && response.data.code !== 200) {
      return Promise.reject(new Error(response.data.msg || '操作失败'));
    }
    return response.data;
  },
  (error) => {
    let errorMessage = '请求失败，请稍后重试';

    if (error.response) {
      // 优先显示后端 message 字段
      if (error.response.data && error.response.data.message) {
        errorMessage = error.response.data.message;
      } else if (error.response.data && error.response.data.msg) {
        errorMessage = error.response.data.msg;
      } else {
        switch (error.response.status) {
          case 400:
            errorMessage = '请求参数错误';
            break;
          case 401:
            errorMessage = '身份验证失败，请重新登录';
            localStorage.removeItem('token');
            window.location.href = '/login';
            break;
          case 403:
            errorMessage = '权限不足';
            break;
          case 404:
            errorMessage = '请求资源不存在';
            break;
          case 500:
            errorMessage = '服务器内部错误';
            break;
          default:
            errorMessage = '请求失败，请稍后重试';
        }
      }
    } else if (error.code === 'ECONNABORTED') {
      // 请求超时
      errorMessage = '请求超时，请检查网络连接';
    } else if (error.message.includes('Network Error')) {
      // 网络错误
      errorMessage = '网络连接失败，请检查网络';
    }

    // 显示错误提示
    ElMessage.error(errorMessage);
    console.error('[API 错误]', errorMessage, error);

    return Promise.reject(new Error(errorMessage));
  }
);

// 通用请求方法封装
const request = {
  get: (url, params = {}, config = {}) => apiClient.get(url, { params, ...config }),
  post: (url, data = {}, config = {}) => apiClient.post(url, data, config),
  put: (url, data = {}, config = {}) => apiClient.put(url, data, config),
  delete: (url, params = {}, config = {}) => apiClient.delete(url, { params, ...config }),
  upload: (url, formData, config = {}) => 
    apiClient.post(url, formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
      ...config
    })
};

// 接口模块 - 登入相关
export const auth = {
  login: (data) => request.post('/user/login', data),
  sendResetCode: (email) => request.post('/user/send-verification-code', { email }),
  register: (data) => request.post('/user/register', data),
  resetPassword: (data) => request.post('/user/reset-password', data),
  logout: () => request.post('/user/logout')
};

// 接口模块 - 用户相关
export const user = {
  getMe: () => request.get('/user/me'),
  updateProfile: (data) => {
    // 兼容 FormData（含头像上传）和普通对象（仅昵称/简介）
    if (data instanceof FormData) {
      return request.upload('/user/update-profile', data);
    } else {
      return request.post('/user/update-profile', data);
    }
  },
  getProfile: (userId) => request.get(`/user/${userId}`),
  getPosts: (userId, page = 1, pageSize = 30) => request.get(`/user/${userId}/posts`, { page, pageSize }),
  updatePassword: (data) => request.post('/user/update-password', data),
  getUserList: (params) => request.get('/user/list', params)
};

// 接口模块 - 验证码相关
export const verification = {
  sendEmailCode: (email) => request.post('/verification/email', { email }),
};

// 作品相关
export const post = {
  getPaged: (params) => request.get('/posts/paged', params),
  publish: (formData) => request.upload('/posts/publish', formData),
  getById: (id) => request.get(`/posts/${id}`),
  toggleLike: (id) => request.post(`/posts/${id}/like`),
};

// 好友相关
export const friend = {
  getList: () => request.get('/friend'),
  add: (userId) => request.post('/friend/add', { userId }),
  accept: (id) => request.post(`/friend/accept/${id}`),
  reject: (id) => request.post(`/friend/reject/${id}`),
  delete: (id) => request.delete(`/friend/${id}`)
};

// 系统通知相关
export const systemMessage = {
  list: (params = {}) => request.get('/system-message/list', params),
  markRead: (id) => request.post(`/system-message/read/${id}`)
};

// 首页内容相关
export const home = {
  getHomeData: () => request.get('/home/data'),
};

// 评论相关的 API
export const commentApi = {
  // 获取指定目标的评论列表
  getCommentsByTarget: async (targetType, targetId) => {
    return await apiClient.get(`/comments/${targetType}/${targetId}`);
  },

  // 获取评论的回复列表
  getReplies: async (commentId) => {
    return await apiClient.get(`/comments/${commentId}/replies`);
  },

  // 添加评论
  addComment: async (targetType, targetId, content, parentId = null) => {
    const url = parentId 
      ? `/comments/${targetType}/${targetId}/${parentId}`
      : `/comments/${targetType}/${targetId}`;
    return await apiClient.post(url, { content });
  },

  // 删除评论
  deleteComment: async (commentId) => {
    return await apiClient.delete(`/comments/${commentId}`);
  }
};

// 通知相关的 API
export const notificationApi = {
  // 获取通知列表
  getNotifications: async () => {
    return await apiClient.get('/notifications');
  },

  // 获取未读通知数量
  getUnreadCount: async () => {
    return await apiClient.get('/notifications/unread');
  },

  // 标记通知为已读
  markAsRead: async (notificationId) => {
    return await apiClient.put(`/notifications/${notificationId}/read`);
  },

  // 标记所有通知为已读
  markAllAsRead: async () => {
    return await apiClient.put('/notifications/read-all');
  },

  // 删除通知
  deleteNotification: async (notificationId) => {
    return await apiClient.delete(`/notifications/${notificationId}`);
  }
};

// 主页 API
export const homeApi = {
  // 获取首页数据
  getHomeData: async () => {
    return await apiClient.get('/home');
  },

  // 获取校园通知
  getNotices: async (limit = 6) => {
    return await apiClient.get('/home/notices', { params: { limit } });
  },

  // 获取热门话题
  getTopics: async (limit = 6) => {
    return await apiClient.get('/home/topics', { params: { limit } });
  },

  // 获取活动列表
  getActivities: async (limit = 15) => {
    return await apiClient.get('/home/activities', { params: { limit } });
  },

  // 获取市场列表
  getMarketItems: async (limit = 15) => {
    return await apiClient.get('/home/market', { params: { limit } });
  }
};

// 导出完整 API 客户端
export default {
  ...apiClient,
  request,
  auth,
  user,
  verification,
  post,
  friend,
  systemMessage,
  home,
  commentApi,
  notificationApi,
  homeApi,
};
